package com.wfm.mianshi.生产消费模型;
import java.util.LinkedList;
import java.util.Queue;
public class 利用非线程安全队列加synchronized {
    // 共享资源类
    static class SharedResource {
        private final Queue<Integer> queue = new LinkedList<>();
        private static final int MAX_SIZE = 5;

        // 生产者方法
        public synchronized void produce(int item) throws InterruptedException {
            while (queue.size() == MAX_SIZE) {
                // 队列已满，生产者等待
                wait();
            }
            queue.add(item);
            System.out.println("生产者生产: " + item);
            // 通知消费者有新数据
            notifyAll();
        }

        // 消费者方法
        public synchronized int consume() throws InterruptedException {
            while (queue.isEmpty()) {
                // 队列为空，消费者等待
                wait();
            }
            int item = queue.poll();
            System.out.println("消费者消费: " + item);
            // 通知生产者有空间可用
            notifyAll();
            return item;
        }
    }

    // 生产者类
    static class Producer implements Runnable {
        private final SharedResource sharedResource;

        public Producer(SharedResource sharedResource) {
            this.sharedResource = sharedResource;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    sharedResource.produce(i);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    // 消费者类
    static class Consumer implements Runnable {
        private final SharedResource sharedResource;

        public Consumer(SharedResource sharedResource) {
            this.sharedResource = sharedResource;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    sharedResource.consume();
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();
        Thread producerThread = new Thread(new Producer(sharedResource));
        Thread consumerThread = new Thread(new Consumer(sharedResource));

        producerThread.start();
        consumerThread.start();

        try {
            producerThread.join();
            consumerThread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

}
